<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;

class Login extends Base
{
    public function index() {
    	
    	/*$salt = substr(uniqid(),-6);
    	dump($salt);
    	halt(CorePwd('123456',$salt));*/
    	$this->assign('portname','政企');
    	$this->view->engine->layout(false); 
        return $this->out();

    }
    
    public function supervise() {
    	
    	/*$salt = substr(uniqid(),-6);
    	dump($salt);
    	halt(CorePwd('123456',$salt));*/
    	session('port','supervise');
    	$this->assign('portname','监管');
    	$this->view->engine->layout(false); 
        return $this->out('index');

    }
    
    public function signin(){
		
		$P = input('param.');
		
		//兼容手机
		$field = 'username';
		if($P['mobile'] && \Tool\check::mobile($P['mobile'])) {
			$field = 'mobile';
			$P['account'] = $P['mobile'];
		}
		//判断类型
		$user = Db::name('user')->where($field,$P['account'])->whereNull('delete_time')->fetchSql(0)->find();
		if(!$user ){
			return $this->error('无此用户！');
		} elseif( $user['state'] != 1){
			return $this->error('此用户已被禁用！');
		} elseif ( $field == 'username' && CorePwd($P['password'],$user['salt']) != $user['password']  ) {
			return $this->error('密码错误！');
		} elseif ( $field == 'mobile' ) {
			//检查验证码
			$sms = Db::name('sms')->where(['mobile'=>$P['mobile'], 'code' => $P['sms_code'],'state' => 1 ])->where('send_time','>',time()-1800 )->fetchSql(0)->find();
			if(!$sms){
				return $this->error('验证码不正确！');
			}
			
			//更新所有验证码已使用
			Db::name('sms')->where('id',$sms['id'])->setField('state',9);
		}
		
		/*if(!$captcha->check($P['verify'])){
			return $this->_tip('验证码错误','verify');
		}*/
		
		$user['expire'] = $P['remember'] ? 3600*24*7 : 3600*24;
		//写入COOKIE\SESSION
//		$this->ip = request()->ip();
		$this->_login($user);
        
        //日记
        $log = [
            'router' => 'login',
        ];
        $this->_log($log);
		
		//登录信息
//		Db::name('UserProfile')->where('user_id',$user['user_id'])->exp('lastlogin','NOW()')->update(['lastip'=>$this->ip]);
		if($P['refer']) {
			$url = $P['refer'];
		} else {
			$url = cookie('_refer') ?: url('/admin');
		}
		
		return $this->success('登录成功',$url);
	}
	
	public function singout() {
		
		if(session('port') == 'supervise'){
			$url = 'login/supervise';
		} else {
			$url = 'login/index';
		}
		
		cookie('user_id',null);
		return redirect($url);
	}
	//发送短信
	public function sms() {
		
		$mobile = input('post.mobile');
		//短信验证码
		$code = rand(100000,999999);
		
		if( $mobile ) {
			
			$user = Db::name('user')->where('mobile',$mobile)->whereNull('delete_time')->find();
			
			if(!$user) {
				return $this->error('抱歉无此手机号的用户');
			} elseif($user['state'] != 1) {
				return $this->error('此手机号的用户已经禁用');
			}
			
			//
			$send_time = session('send_sms');
			$rest_time = time() - $send_time;
			if( $rest_time < 60) {
				return $this->error('验证码已发送，请在'.$rest_time.'秒后重试。' );
			}
			
			if(\Tool\check::mobile($mobile)  !== true ) {
				return $this->error('手机号码不正确');
			}
			//查询是否有帐号
//			$user = Db::name('user')->where(['mobile'=>$mobile,'state'=>1])->find();
			
			/*if( !$user ) {
				return $this->error('查无此帐号');
			}*/
			
		} else {
			return $this->error('手机号码不正确');
		}
		
//		halt($code);
		$params = array ();
   	 	// *** 需用户填写部分 ***
	    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
	    $accessKeyId = "LTAIBVa52ezFVxQQ";
	    $accessKeySecret = "yH32TJNVAverIZdErQk3nAtwIVH5v6";

	    // fixme 必填: 短信接收号码
	    $params["PhoneNumbers"] = $mobile;

	    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
	    $params["SignName"] = "晋江出行";

	    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
	    $params["TemplateCode"] = "SMS_62840083";

	    // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
	    $params['TemplateParam'] = Array (
	        "code" => $code,
	    );


	    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
	    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
	        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
	    }

	    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
	    $helper = new \Tool\signaturehelper();

	    // 此处可能会抛出异常，注意catch
	    $content = $helper->request(
	        $accessKeyId,
	        $accessKeySecret,
	        "dysmsapi.aliyuncs.com",
	        array_merge($params, array(
	            "RegionId" => "cn-hangzhou",
	            "Action" => "SendSms",
	            "Version" => "2017-05-25",
	        ))
	    );
	    
	    if($content->Code == 'OK') {
	    	
	    	//插入手机验证
	    	Db::name('sms')->where('mobile',$mobile)->setField('state',9);#禁用旧的
			Db::name('sms')->insert(['mobile'=>$mobile,'code'=>$code,'send_time'=>time()]);
	    	$msg = $content->Message;
	    	session('send_sms',time());
			$rslt = 1;
		} else {
			$rslt = 0;
			$msg = '因网络问题未成功发送，请重试。';
		}
	    
	    return $this->res($rslt,$content->Message);
	}
	
    //登录
	protected function _login($data, $log = 1) {
		
		cookie('user_id',StrEncrypt($data['user_id']),intval($data['expire']));
		cookie('user_check',StrEncrypt($data['password']),intval($data['expire']));
		session('user_id',$data['user_id']);
		$this->uid = $data['user_id'];
		//操作日记
	}
    
}
